package com.mars.module.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mars.common.response.PageInfo;
import com.mars.framework.context.ContextUserInfoThreadHolder;
import com.mars.framework.exception.ServiceException;
import com.mars.module.admin.entity.SysFood;
import com.mars.module.admin.mapper.SysFoodMapper;
import com.mars.module.admin.service.ISysDictDataService;
import com.mars.module.system.entity.SysUser;
import com.mars.module.system.mapper.SysUserMapper;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import com.mars.module.admin.request.SysBusinessRequest;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import com.mars.module.admin.mapper.SysBusinessMapper;
import org.springframework.beans.BeanUtils;
import com.mars.module.admin.entity.SysBusiness;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.mars.module.admin.service.ISysBusinessService;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 业务记录业务层处理
 *
 * @author mars
 * @date 2024-04-02
 */
@Slf4j
@Service
@AllArgsConstructor
public class SysBusinessServiceImpl implements ISysBusinessService {

    private final SysBusinessMapper baseMapper;
    private final SysFoodMapper foodMapper;
    private final SysUserMapper userMapper;
    private final ISysDictDataService iSysDictDataService;


    private String getSerialNo(String prefix) {
        return prefix + System.currentTimeMillis();
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public SysBusiness add(SysBusinessRequest request) {
        SysBusiness entity = SysBusiness.builder().build();
        BeanUtils.copyProperties(request, entity);
        SysFood sysFood = foodMapper.selectById(request.getFoodId());
        String serialNo = "";
        //1-入库 2-出库
        if ("1".equals(request.getType())) {
            //更新库存
            sysFood.setAmount(sysFood.getAmount() + request.getAmount());
            serialNo = getSerialNo("RK");
        } else if ("2".equals(request.getType())) {
            if (sysFood.getAmount() < request.getAmount()) {
                throw new ServiceException("粮食库存不足！无法出库！");
            } else {
                //更新库存
                sysFood.setAmount(sysFood.getAmount() - request.getAmount());
                serialNo = getSerialNo("CK");
            }
        }
        foodMapper.updateById(sysFood);
        Long userId = ContextUserInfoThreadHolder.get().getId();
        entity.setCreateById(userId);
        entity.setSerialNo(serialNo);
        baseMapper.insert(entity);
        return entity;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean delete(Long id) {
        return baseMapper.deleteById(id) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteBatch(List<Long> ids) {
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean update(SysBusinessRequest request) {
        SysBusiness entity = SysBusiness.builder().build();
        BeanUtils.copyProperties(request, entity);
        return baseMapper.updateById(entity) > 0;
    }

    @Override
    public SysBusiness getById(Long id) {
        return baseMapper.selectById(id);
    }

    @Override
    public PageInfo<SysBusiness> pageList(SysBusinessRequest request) {
        Page<SysBusiness> page = new Page<>(request.getPageNo(), request.getPageSize());
        LambdaQueryWrapper<SysBusiness> query = this.buildWrapper(request);
        IPage<SysBusiness> pageRecord = baseMapper.selectPage(page, query);
        List<SysBusiness> records = pageRecord.getRecords();
        List<SysBusiness> recordsNew = new ArrayList<>();
        for (SysBusiness collection : records) {
            SysUser sysUser = userMapper.selectById(collection.getCreateById());
            collection.setCreateName(sysUser == null ? "" : sysUser.getUserName());
            SysFood sysFood = foodMapper.selectById(collection.getFoodId());
            collection.setFoodName(sysFood == null ? "" : sysFood.getName());
            collection.setType(iSysDictDataService.getDictDataById("transfer_type", collection.getType()));
            recordsNew.add(collection);
        }
        if (StringUtils.isNotBlank(request.getFoodName())) {
            recordsNew = recordsNew.stream().filter(e -> e.getFoodName().contains(request.getFoodName())).collect(Collectors.toList());
        }
        pageRecord.setRecords(recordsNew);
        return PageInfo.build(pageRecord);
    }


    @Override
    public List<SysBusiness> list(SysBusinessRequest request) {
        LambdaQueryWrapper<SysBusiness> query = this.buildWrapper(request);
        return baseMapper.selectList(query);
    }

    private LambdaQueryWrapper<SysBusiness> buildWrapper(SysBusinessRequest param) {
        LambdaQueryWrapper<SysBusiness> query = new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank(param.getSerialNo())) {
            query.like(SysBusiness::getSerialNo, param.getSerialNo());
        }
        if (StringUtils.isNotBlank(param.getType())) {
            query.like(SysBusiness::getType, param.getType());
        }
        return query;
    }

}
